package ge.modules.utils;

import java.util.HashMap;

import ge.engine.Log;
import ge.exceptions.FunctionNonSuported;
import ge.lowlevel.UtilityEngine;
import ge.modules.Module;

public class WebCallModule implements Module, IWebCallModule
{
	private String urlCall,data;
	private WebCallState state;
	private HashMap<String, String> requestParams;

	public WebCallModule(String url)
	{
		this.urlCall = url;
		data = ""; 
		state = WebCallState.NOT_SEND;
		requestParams = new HashMap<String,String>();
	}
	/**
	 * 	New value to the call
	 * @param name	Param name
	 * @param value Param value
	 */
	public void setParam(String name, String value)
	{
		requestParams.put(name, value);
	}
	
	public void removeParam(String name)
	{
		requestParams.remove(name);
	}
	/**
	 * 	Returns a param value
	 * @param name Param name
	 */
	public String getParam(String name)
	{
		return requestParams.get(name);
	}
	@Override
	public String getCall() {
		 return urlCall;
	}

	public boolean isMessageSent()
	{
		return state == WebCallState.SENT;
	}
	@Override
	public String getRequestData() {
		 try {
			String params =  UtilityEngine.get().formatRequestParams(requestParams);
			//Log.write(getCall()+"?"+params);
	 
			return params;
		} catch (FunctionNonSuported e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 return "";
	}

	public void send()
	{
		try {
			UtilityEngine.get().callPostUrl(this);
		} catch (FunctionNonSuported e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void remoteSend()
	{
		try {
			int id = UtilityEngine.getCallbackId();
			 
			this.setParam("callback", "callback"+id);
			UtilityEngine.get().remoteCall(id, this);
		} catch (FunctionNonSuported e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.removeParam("callback");
	}
	@Override
	public WebCallState getState() 
	{
		return state;
	}

	@Override
	public String getStateMessage() {
		return data;
	}

	@Override
	public void setState(WebCallState state, String message) {
		this.state = state;
		data = message;
		
	}

	@Override
	public void setContent(String message) {
		this.setState(WebCallState.SENT, message);
		//Log.write("Recived Content in WebCallModule "+message);
		
	}

	@Override
	public void setError(String message) {
		this.setState(WebCallState.ERROR, message);
		
	}
	@Override
	public void update() {
	 
		
	}
	@Override
	public void draw() {
		 
		
	}
	@Override
	public void delete() {
		 
		
	}

}
